import { classesOptions, createForm, questionsOptions } from "@/models/contestManage";
import axios from "axios";
import { globalUrl, normalHeaders, verifyHeaders } from "./global";

async function toGetClasses(): Promise<classesOptions[] | null>{
    try {
        const data: classesOptions[] = [];
        const res = await axios.get(globalUrl + 'sql/classes/gets?limit=100', {headers: normalHeaders});
        if (res.status == 200 && res.data.code == 0){
            for (let i = 0; i < res.data.classes_.length; i++){
                data.push({
                    label: res.data.classes_[i].name,
                    value: res.data.classes_[i].id
                });
            }
            return data;
        } else {
            return null;
        }
    } catch (error) {
        console.log(error);
        return null;
    }
}

async function toGetQuestions(): Promise<questionsOptions[] | null>{
    try {
        const data: questionsOptions[] = [];
        const res = await axios.get(globalUrl + 'sql/questions/gets?limit=100', {headers: normalHeaders});
        if (res.status == 200 && res.data.code == 0){
            for (let i = 0; i < res.data.questions.length; i++){
                data.push({
                    label: String(res.data.questions[i].Questions.question_id) + ' ' + String(res.data.questions[i].Questions.name),
                    value: res.data.questions[i].Questions.id
                });
            }
            return data;
        } else {
            return null;
        }
    } catch (error) {
        console.log(error);
        return null;
    }
}

async function toCreateContest(contestForm: createForm){
    try {
        const res = await axios.post(globalUrl + 'sql/contests/create', contestForm, {headers: verifyHeaders});
        if (res.status == 200 && res.data.code == 0) {
            return res.data.contest_.contest_id;
        } else {
            return 0;
        }
    } catch (error) {
        console.log(error);
        return -1;
    }
}

export { toGetClasses, toGetQuestions, toCreateContest };